package com.huashi.dealer.modular.business.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huashi.dealer.commonEntity.*;
import com.huashi.dealer.core.component.DataScopeInfo;
import com.huashi.dealer.core.util.PasswordUtil;
import com.huashi.dealer.core.util.TimeUtil;
import com.huashi.dealer.modular.business.address.mapper.UserAddressMapper;
import com.huashi.dealer.modular.business.goods.mapper.GoodsImageMapper;
import com.huashi.dealer.modular.business.goods.mapper.GoodsMapper;
import com.huashi.dealer.modular.business.region.mapper.RegionMapper;
import com.huashi.dealer.modular.business.user.mapper.UserBalanceLogMapper;
import com.huashi.dealer.modular.business.user.mapper.UserRebateLogMapper;
import com.huashi.dealer.modular.business.user.mapper.UserWriteoffLogMapper;
import com.huashi.dealer.modular.business.user.mapper.UserMapper;
import com.huashi.dealer.modular.business.user.mapper.StoreUserMapper;
import com.huashi.dealer.modular.business.user.mapper.StoreUserRuleMapper;
import com.huashi.dealer.modular.business.balance.mapper.UserRechargeReviewMapper;
import com.huashi.dealer.modular.business.user.param.StoreUserListParam;
import com.huashi.dealer.modular.business.user.param.StoreUserSaveParam;
import com.huashi.dealer.modular.business.user.param.StoreUserRechargeParam;
import com.huashi.dealer.modular.business.user.param.StoreUserRechargeApplyParam;
import com.huashi.dealer.modular.business.user.param.StoreUserAddressListParam;
import com.huashi.dealer.modular.business.user.param.StoreUserAddressSaveParam;
import com.huashi.dealer.modular.business.user.param.StoreUserSalesmanParam;
import com.huashi.dealer.modular.business.user.service.StoreUserManageService;
import com.huashi.dealer.modular.business.user.vo.StoreUserListVo;
import com.huashi.dealer.modular.business.user.vo.StoreUserDetailVo;
import com.huashi.dealer.modular.business.user.vo.StoreUserAddressListVo;
import com.huashi.dealer.modular.business.user.vo.StoreUserAddressDetailVo;
import com.huashi.dealer.modular.business.user.vo.StoreUserSalesmanVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Store端用户管理服务实现类
 *
 * @author 谭陈强
 * @since 2025-08-07
 */
@Slf4j
@Service
public class StoreUserManageServiceImpl extends ServiceImpl<UserMapper, User> implements StoreUserManageService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserBalanceLogMapper userBalanceLogMapper;

    @Resource
    private UserRebateLogMapper userRebateLogMapper;

    @Resource
    private UserWriteoffLogMapper userWriteoffLogMapper;

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private RegionMapper regionMapper;
    
    @Resource
    private StoreUserMapper storeUserMapper;
    
    @Resource
    private StoreUserRuleMapper storeUserRuleMapper;
    
    @Resource
    private DataScopeInfo dataScopeInfo;

    @Resource
    private UserRechargeReviewMapper userRechargeReviewMapper;

    @Resource
    private UserAddressMapper userAddressMapper;
    @Autowired
    private GoodsImageMapper goodsImageMapper;

    @Override
    public Page<StoreUserListVo> getUserList(StoreUserListParam param, Page<User> page) {

        // 构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

//        List<Long> userIds = dataScopeInfo.getUserIds();
//        if(userIds.size() == 0){
//            Page<StoreUserListVo> resultPage = new Page<>();
//            BeanUtils.copyProperties(page, resultPage);
//            return resultPage;
//        }else{
//            if(dataScopeInfo.identity()!= -1){
//                queryWrapper.in(User::getUserId, userIds);
//            }
//        }


        // 搜索条件
        if (StringUtils.hasText(param.getSearch())) {
            queryWrapper.and(wrapper -> wrapper
                .like(User::getNickName, param.getSearch())
                .or()
                .like(User::getRealName, param.getSearch())
                .or()
                .like(User::getMobile, param.getSearch())
            );
        }

        // 地域筛选
        if (param.getProvinceId() != null) {
            queryWrapper.eq(User::getProvinceId, param.getProvinceId());
        }
        if (param.getCityId() != null) {
            queryWrapper.eq(User::getCityId, param.getCityId());
        }
        if (param.getRegionId() != null) {
            queryWrapper.eq(User::getRegionId, param.getRegionId());
        }

        // 会员等级筛选
        if (param.getGradeId() != null) {
            queryWrapper.eq(User::getGradeId, param.getGradeId());
        }

        // 排序
        queryWrapper.orderByDesc(User::getCreateTime);

        // 分页查询
        Page<User> userPage = userMapper.selectPage(page, queryWrapper);

        // 转换为VO
        Page<StoreUserListVo> resultPage = new Page<>();
        BeanUtils.copyProperties(userPage, resultPage);

        List<StoreUserListVo> voList = userPage.getRecords().stream()
            .map(this::convertToStoreUserListVo)
            .collect(Collectors.toList());

        resultPage.setRecords(voList);
        return resultPage;
    }

    @Override
    public StoreUserDetailVo getUserDetail(Long userId) {
        // 查询用户基本信息
        User user = userMapper.selectById(userId);
        if (user == null || user.getIsDelete() == 1) {
            throw new RuntimeException("用户不存在");
        }

        // 转换为详情VO
        StoreUserDetailVo detailVo = new StoreUserDetailVo();
        BeanUtils.copyProperties(user, detailVo);
        detailVo.setCreateTime(TimeUtil.changeToLocalDateTime(user.getCreateTime()));
        // 设置地域信息
        if (user.getProvinceId() != null) {
            StoreUserDetailVo.RegionVo regionVo = new StoreUserDetailVo.RegionVo();
            regionVo.setProvinceId(user.getProvinceId());
            regionVo.setCityId(user.getCityId());
            regionVo.setRegionId(user.getRegionId());
            
            // 查询地域名称
            Region province = regionMapper.selectById(user.getProvinceId());
            Region city = regionMapper.selectById(user.getCityId());
            Region region = regionMapper.selectById(user.getRegionId());
            
            if (province != null) regionVo.setProvince(province.getName());
            if (city != null) regionVo.setCity(city.getName());
            if (region != null) regionVo.setRegion(region.getName());
            
            detailVo.setRegion(regionVo);
        }

        // 设置上级业务员信息
        if (user.getStoreUserId() != null) {
            StoreUser storeUser = storeUserMapper.selectById(user.getStoreUserId());
            if (storeUser != null) {
                StoreUserDetailVo.StoreUserVo storeUserVo = new StoreUserDetailVo.StoreUserVo();
                storeUserVo.setStoreUserId(storeUser.getStoreUserId());
                storeUserVo.setRealName(storeUser.getUserName());
                storeUserVo.setMobile(storeUser.getMobile());
                detailVo.setStoreUser(storeUserVo);
            }
        }

        // 设置不可查看商品列表
        if (StringUtils.hasText(user.getGoodsIds())) {
            String[] goodsIds = user.getGoodsIds().split(",");
            List<StoreUserDetailVo.GoodsVo> goodsList = goodsMapper.selectBatchIds(
                    List.of(goodsIds).stream()
                            .map(Long::valueOf)
                            .collect(Collectors.toList())
            ).stream().map(goods -> {
                StoreUserDetailVo.GoodsVo goodsVo = new StoreUserDetailVo.GoodsVo();
                goodsVo.setGoodsId(goods.getGoodsId());
                goodsVo.setGoodsName(goods.getGoodsName());
                List<String> goodsImages = goodsImageMapper.getFileUrlByGoodsId(goods.getGoodsId());
                goodsVo.setImagePath(goodsImages);
                return goodsVo;
            }).collect(Collectors.toList());
            detailVo.setGoodsList(goodsList);
        }

        // 设置账户余额（直接从User表获取）
        detailVo.setBalance(user.getBalance());
        detailVo.setRebate(user.getRebate());
        detailVo.setWriteoff(user.getWriteoff());

        return detailVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUser(StoreUserSaveParam param) {
        // 参数验证
        validateUserParam(param);

        // 检查账号是否已存在
        User existingUser = userMapper.selectOne(
            new LambdaQueryWrapper<User>()
                .eq(User::getAccount, param.getAccount())
        );
        if (existingUser != null) {
            throw new RuntimeException("该账号已存在，请重试！");
        }

        // 创建用户
        User user = new User();
        BeanUtils.copyProperties(param, user);
        user.setPassword(encryptPassword(param.getPassword()));
        user.setGoodsIds(param.getGoodsIds() != null ? 
            param.getGoodsIds().stream().map(String::valueOf).collect(Collectors.joining(",")) : "");
        user.setCreateTime(System.currentTimeMillis() / 1000);
        user.setIsDelete(0);
        
        // 设置默认值
        user.setBalance(BigDecimal.ZERO);
        user.setRebate(BigDecimal.ZERO);
        user.setWriteoff(BigDecimal.ZERO);

        userMapper.insert(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editUser(StoreUserSaveParam param) {
        // 参数验证
        if (param.getUserId() == null) {
            throw new RuntimeException("用户ID不能为空");
        }
//        validateUserParam(param);

        // 检查用户是否存在
        User existingUser = userMapper.selectById(param.getUserId());
        if (existingUser == null || existingUser.getIsDelete() == 1) {
            throw new RuntimeException("用户不存在");
        }

        // 检查账号是否已被其他用户使用
        User duplicateUser = userMapper.selectOne(
            new LambdaQueryWrapper<User>()
                .eq(User::getAccount, param.getAccount())
                .ne(User::getUserId, param.getUserId())
        );
        if (duplicateUser != null) {
            throw new RuntimeException("该账号已存在，请重试！");
        }

        // 更新用户信息
        User user = new User();
        BeanUtils.copyProperties(param, user);
        if (StringUtils.hasText(param.getPassword())) {
            user.setPassword(encryptPassword(param.getPassword()));
        }
        user.setGoodsIds(param.getGoodsIds() != null ? 
            param.getGoodsIds().stream().map(String::valueOf).collect(Collectors.joining(",")) : "");
        user.setUpdateTime(System.currentTimeMillis() / 1000);

        userMapper.updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Long userId) {
        // 检查用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null || user.getIsDelete() == 1) {
            throw new RuntimeException("用户不存在");
        }

        // 软删除用户
      userMapper.deleteById(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rechargeUser(StoreUserRechargeParam param) {
        // 检查用户是否存在
        User user = userMapper.selectById(param.getUserId());
        if (user == null || user.getIsDelete() == 1) {
            throw new RuntimeException("用户不存在");
        }

        // 处理充值
        if (param.getBalance() != null && StringUtils.hasText(param.getBalance().getRemark())) {
            processRecharge(user, param.getBalance(), "balance", "基本账户");
        }
        if (param.getRebate() != null && StringUtils.hasText(param.getRebate().getRemark())) {
            processRecharge(user, param.getRebate(), "rebate", "返利账户");
        }
        if (param.getWriteoff() != null && StringUtils.hasText(param.getWriteoff().getRemark())) {
            processRecharge(user, param.getWriteoff(), "writeoff", "核销账户");
        }

        // 更新用户余额
        userMapper.updateById(user);

        // 记录充值日志
        recordRechargeLog(param);
    }

    @Override
    public void rechargeApply(StoreUserRechargeApplyParam param) {
        // 检查用户是否存在
        User user = userMapper.selectById(param.getUserId());
        if (user == null || user.getIsDelete() == 1) {
            throw new RuntimeException("用户不存在");
        }

        // 获取当前登录的后台用户ID
        Long storeUserId = dataScopeInfo.getCurrentStoreUserId();

        // 处理充值申请
        if (param.getBalance() != null && param.getSource() == 0) {
            saveRechargeReview(user.getUserId(), storeUserId, 0, param.getBalance());
        }
        if (param.getRebate() != null && param.getSource() == 1) {
            saveRechargeReview(user.getUserId(), storeUserId, 1, param.getRebate());
        }
        if (param.getWriteoff() != null && param.getSource() == 2) {
            saveRechargeReview(user.getUserId(), storeUserId, 2, param.getWriteoff());
        }
    }

    /**
     * 保存充值申请记录到user_recharge_review表
     */
    private void saveRechargeReview(Long userId, Long storeUserId, Integer source,
                                   StoreUserRechargeApplyParam.RechargeInfo rechargeInfo) {
        UserRechargeReview review = new UserRechargeReview();
        review.setUserId(userId);
        review.setStoreUserId(storeUserId);
        review.setSource(source);
        review.setMode(rechargeInfo.getMode());
        review.setPrice(new BigDecimal(rechargeInfo.getMoney()));
        review.setRemark(rechargeInfo.getRemark());
        review.setWxappId(10001L); // 默认小程序ID
        review.setCreateTime(System.currentTimeMillis() / 1000);
        review.setUpdateTime(System.currentTimeMillis() / 1000);

        userRechargeReviewMapper.insert(review);
    }

    /**
     * 转换为用户列表VO
     */
    private StoreUserListVo convertToStoreUserListVo(User user) {
        StoreUserListVo vo = new StoreUserListVo();
        BeanUtils.copyProperties(user, vo);
        // 设置地域信息
        if (user.getProvinceId() != null) {
            StoreUserListVo.RegionVo regionVo = new StoreUserListVo.RegionVo();
            
            // 查询地域名称
            Region province = regionMapper.selectById(user.getProvinceId());
            Region city = regionMapper.selectById(user.getCityId());
            Region region = regionMapper.selectById(user.getRegionId());
            
            if (province != null) regionVo.setProvince(province.getName());
            if (city != null) regionVo.setCity(city.getName());
            if (region != null) regionVo.setRegion(region.getName());
            
            vo.setRegion(regionVo);
        }

        // 设置账户余额（直接从User表获取）
        vo.setBalance(user.getBalance());
        vo.setRebate(user.getRebate());
        vo.setWriteoff(user.getWriteoff());
        vo.setCreateTime(TimeUtil.changeToLocalDateTime(user.getCreateTime()));

        // 设置完成进度
        vo.setProgress(user.getPercentage());

        return vo;
    }

    /**
     * 验证用户参数
     */
    private void validateUserParam(StoreUserSaveParam param) {
        if (!StringUtils.hasText(param.getAccount())) {
            throw new RuntimeException("账号不能为空");
        }
        if (!StringUtils.hasText(param.getNickName())) {
            throw new RuntimeException("请输入正确的名称！");
        }
        if (!StringUtils.hasText(param.getRealName())) {
            throw new RuntimeException("请输入正确的联系人！");
        }
        if (!StringUtils.hasText(param.getMobile())) {
            throw new RuntimeException("请输入正确的手机号！");
        }
        if (param.getStoreUserId() == null) {
            throw new RuntimeException("请选择上级业务员！");
        }
        if (StringUtils.hasText(param.getPassword()) && !param.getPassword().equals(param.getPasswordConfirm())) {
            throw new RuntimeException("两次输入的密码不一致");
        }
    }

    /**
     * 加密密码
     */
    private String encryptPassword(String password) {
        password= PasswordUtil.yoshopHash(password);
        return password;
    }

    /**
     * 处理充值
     */
    private void processRecharge(User user, StoreUserRechargeParam.RechargeInfo rechargeInfo, 
                                String accountType, String accountName) {
        BigDecimal amount = new BigDecimal(rechargeInfo.getMoney());
        BigDecimal currentBalance = getAccountBalance(user, accountType);
        
        if ("inc".equals(rechargeInfo.getMode())) {
            // 增加
            setAccountBalance(user, accountType, currentBalance.add(amount));
        } else if ("dec".equals(rechargeInfo.getMode())) {
            // 减少
            BigDecimal newBalance = currentBalance.subtract(amount);
            if(!accountType.equals("balance")) {
                if (newBalance.compareTo(BigDecimal.ZERO) < 0) {
                    throw new RuntimeException(accountName + "余额不足，无法减少");
                }
            }
            setAccountBalance(user, accountType, newBalance);
        }
    }

    /**
     * 获取账户余额
     */
    private BigDecimal getAccountBalance(User user, String accountType) {
        switch (accountType) {
            case "balance": return user.getBalance() != null ? user.getBalance() : BigDecimal.ZERO;
            case "rebate": return user.getRebate() != null ? user.getRebate() : BigDecimal.ZERO;
            case "writeoff": return user.getWriteoff() != null ? user.getWriteoff() : BigDecimal.ZERO;
            default: return BigDecimal.ZERO;
        }
    }

    /**
     * 设置账户余额
     */
    private void setAccountBalance(User user, String accountType, BigDecimal amount) {
        switch (accountType) {
            case "balance": user.setBalance(amount); break;
            case "rebate": user.setRebate(amount); break;
            case "writeoff": user.setWriteoff(amount); break;
        }
    }

    /**
     * 记录充值日志
     */
    private void recordRechargeLog(StoreUserRechargeParam param) {
        if (param.getBalance() != null && StringUtils.hasText(param.getBalance().getRemark())) {
            insertRechargeLog(param.getUserId(), "balance", param.getBalance());
        }
        if (param.getRebate() != null && StringUtils.hasText(param.getRebate().getRemark())) {
            insertRechargeLog(param.getUserId(), "rebate", param.getRebate());
        }
        if (param.getWriteoff() != null && StringUtils.hasText(param.getWriteoff().getRemark())) {
            insertRechargeLog(param.getUserId(), "writeoff", param.getWriteoff());
        }
    }

    /**
     * 插入充值日志
     */
    private void insertRechargeLog(Long userId, String accountType, StoreUserRechargeParam.RechargeInfo rechargeInfo) {
        BigDecimal amount = new BigDecimal(rechargeInfo.getMoney());
        long currentTime = System.currentTimeMillis() / 1000;
        
        if ("balance".equals(accountType)) {
            // 基本账户日志
            UserBalanceLog log = new UserBalanceLog();
            log.setUserId(userId);
            log.setScene(30); // 管理员操作
            log.setMoney(amount);
            log.setDescription("管理员充值操作");
            log.setRemark(rechargeInfo.getRemark());
            log.setCreateTime(currentTime);
            userBalanceLogMapper.insert(log);
        } else if ("rebate".equals(accountType)) {
            // 返利账户日志
            UserRebateLog log = new UserRebateLog();
            log.setUserId(userId);
            log.setScene(30); // 管理员操作
            log.setMoney(amount);
            log.setDescription("管理员充值操作");
            log.setRemark(rechargeInfo.getRemark());
            log.setCreateTime(currentTime);
            userRebateLogMapper.insert(log);
        } else if ("writeoff".equals(accountType)) {
            // 核销账户日志
            UserWriteoffLog log = new UserWriteoffLog();
            log.setUserId(userId);
            log.setScene(30); // 管理员操作
            log.setMoney(amount);
            log.setDescription("管理员充值操作");
            log.setRemark(rechargeInfo.getRemark());
            log.setCreateTime(currentTime);
            userWriteoffLogMapper.insert(log);
        }
    }

    @Override
    public List<StoreUserSalesmanVo> getSalesmanList(StoreUserSalesmanParam param) {
        List<StoreUserSalesmanVo> result = new ArrayList<>();
        
        // 参数验证
        if (param.getProvince() == null && param.getCity() == null) {
            log.warn("省份ID和城市ID不能同时为空");
            return result;
        }
        
        try {
            // 1. 根据省份ID或城市ID查询有权限的业务员ID列表
            // 逻辑：省份ID匹配 或者 城市ID匹配 都可以
            List<Integer> storeUserIds = storeUserRuleMapper.selectStoreUserIdsByRegion(
                param.getProvince(), param.getCity());
            
            if (storeUserIds == null || storeUserIds.isEmpty()) {
                log.info("未找到符合条件的业务员权限规则，省份ID: {}, 城市ID: {}", 
                    param.getProvince(), param.getCity());
                return result;
            }
            
            // 2. 根据业务员ID列表和角色ID查询业务员列表
            // 角色ID: 10006(业务员), 10007(高级业务员)
            List<Integer> roleIds = List.of(10006, 10007);
            List<StoreUser> storeUsers = storeUserMapper.selectSalesmanList(storeUserIds, roleIds);
            
            if (storeUsers == null || storeUsers.isEmpty()) {
                log.info("未找到符合条件的业务员，业务员ID列表: {}, 角色ID列表: {}", 
                    storeUserIds, roleIds);
                return result;
            }
            
            // 3. 转换为VO
            for (StoreUser storeUser : storeUsers) {
                StoreUserSalesmanVo vo = new StoreUserSalesmanVo();
                vo.setStoreUserId(storeUser.getStoreUserId().longValue());
                vo.setUserName(storeUser.getUserName());
                result.add(vo);
            }
            
            log.info("成功获取业务员列表，省份ID: {}, 城市ID: {}, 找到业务员数量: {}", 
                param.getProvince(), param.getCity(), result.size());
            
        } catch (Exception e) {
            log.error("获取业务员列表失败，省份ID: {}, 城市ID: {}", 
                param.getProvince(), param.getCity(), e);
            throw new RuntimeException("获取业务员列表失败：" + e.getMessage());
        }
        
        return result;
    }

    @Override
    public Page<StoreUserAddressListVo>  getUserAddressList(Page<UserAddress> page, StoreUserAddressListParam param) {
        Page<StoreUserAddressListVo> result = new Page<>();
        // 构建查询条件
        LambdaQueryWrapper<UserAddress> queryWrapper =
            new LambdaQueryWrapper<UserAddress>()
                .eq(UserAddress::getUserId, param.getUserId())
                .orderByDesc(UserAddress::getCreateTime);

        // 搜索条件
        if (StringUtils.hasText(param.getSearch())) {
            queryWrapper.and(wrapper -> wrapper
                .like(UserAddress::getName, param.getSearch())
                .or()
                .like(UserAddress::getPhone, param.getSearch())
            );
        }

        // 查询地址列表
        Page<UserAddress> userAddressPage = userAddressMapper.selectPage(page, queryWrapper);

        // 转换为VO并设置地区信息
        List<StoreUserAddressListVo> collect = userAddressPage.getRecords().stream().map(this::convertToStoreUserAddressListVo).collect(Collectors.toList());
        BeanUtils.copyProperties(userAddressPage, result);
        result.setRecords(collect);
        return result;
    }

    @Override
    public StoreUserAddressDetailVo getUserAddressDetail(Long userId, Long addressId) {
        // 查询地址详情
        UserAddress address = userAddressMapper.selectOne(
            new LambdaQueryWrapper<UserAddress>()
                .eq(UserAddress::getUserId, userId)
                .eq(UserAddress::getAddressId, addressId)
        );

        if (address == null) {
            throw new RuntimeException("地址不存在");
        }

        return convertToStoreUserAddressDetailVo(address);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserAddress(StoreUserAddressSaveParam param) {
        // 检查用户是否存在
        User user = userMapper.selectById(param.getUserId());
        if (user == null || user.getIsDelete() == 1) {
            throw new RuntimeException("用户不存在");
        }

        // 创建或更新地址对象
        UserAddress address = new UserAddress();
        BeanUtils.copyProperties(param, address);
        // 设置小程序ID
        address.setWxappId(10001L);

        if (param.getAddressId() == null) {
            // 新增
            address.setCreateTime(System.currentTimeMillis() / 1000);
            address.setUpdateTime(System.currentTimeMillis() / 1000);
        } else {
            // 编辑：检查地址是否存在且属于该用户
            UserAddress existingAddress = userAddressMapper.selectOne(
                new LambdaQueryWrapper<UserAddress>()
                    .eq(UserAddress::getUserId, param.getUserId())
                    .eq(UserAddress::getAddressId, param.getAddressId())
            );

            if (existingAddress == null) {
                throw new RuntimeException("地址不存在");
            }

            // 更新时只设置更新时间
            address.setUpdateTime(System.currentTimeMillis() / 1000);
        }

        // 使用MyBatis-Plus的saveOrUpdate方法统一处理新增和编辑
        if (param.getAddressId() == null) {
            userAddressMapper.insert(address);
        } else {
            userAddressMapper.updateById(address);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserAddress(Long userId, Long addressId) {
        // 检查地址是否存在
        UserAddress address = userAddressMapper.selectOne(
            new LambdaQueryWrapper<UserAddress>()
                .eq(UserAddress::getUserId, userId)
                .eq(UserAddress::getAddressId, addressId)
        );

        if (address == null) {
            throw new RuntimeException("地址不存在");
        }

        // 删除地址
        userAddressMapper.deleteById(addressId);
    }

    /**
     * 转换为StoreUserAddressListVo
     */
    private StoreUserAddressListVo convertToStoreUserAddressListVo(UserAddress address) {
        StoreUserAddressListVo vo = new StoreUserAddressListVo();
        BeanUtils.copyProperties(address, vo);

        vo.setCreateTime(TimeUtil.changeToLocalDateTime(address.getCreateTime()));
        // 设置地区信息
        if (address.getProvinceId() != null) {
            StoreUserAddressListVo.RegionVo regionVo = new StoreUserAddressListVo.RegionVo();

            // 查询地区名称
            Region province = regionMapper.selectById(address.getProvinceId());
            Region city = regionMapper.selectById(address.getCityId());
            Region region = regionMapper.selectById(address.getRegionId());

            if (province != null) regionVo.setProvince(province.getName());
            if (city != null) regionVo.setCity(city.getName());
            if (region != null) regionVo.setRegion(region.getName());

            vo.setRegion(regionVo);
        }
        return vo;
    }

    /**
     * 转换为StoreUserAddressDetailVo
     */
    private StoreUserAddressDetailVo convertToStoreUserAddressDetailVo(UserAddress address) {
        StoreUserAddressDetailVo vo = new StoreUserAddressDetailVo();
        BeanUtils.copyProperties(address, vo);

        // 设置地区信息
        if (address.getProvinceId() != null) {
            StoreUserAddressListVo.RegionVo regionVo = new StoreUserAddressListVo.RegionVo();

            // 查询地区名称
            Region province = regionMapper.selectById(address.getProvinceId());
            Region city = regionMapper.selectById(address.getCityId());
            Region region = regionMapper.selectById(address.getRegionId());

            if (province != null) regionVo.setProvince(province.getName());
            if (city != null) regionVo.setCity(city.getName());
            if (region != null) regionVo.setRegion(region.getName());

            vo.setRegion(regionVo);
        }

        vo.setCreateTime(TimeUtil.changeToLocalDateTime(address.getCreateTime()));
        vo.setUpdateTime(TimeUtil.changeToLocalDateTime(address.getUpdateTime()));
        return vo;
    }
}
